package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.CheckItemDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/10/23 15:57
 * @Version V1.0
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            // 1：新增套餐，向套餐表中添加1条数据
            setmealDao.add(setmeal);
            // 2：新增套餐和检查组的中间表，想套餐和检查组的中间表中插入多条数据
            if(checkgroupIds!=null && checkgroupIds.length>0){
                setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
            }
            // 3：向Redis中集合的key值为setmealPicDbResources下保存数据，数据为图片的名称
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
            jedisPool.getResource().del("setmeals");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("套餐图片不能为空");
        }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        // 初始化分页参数
        PageHelper.startPage(currentPage,pageSize);
        // 查询
        Page<Setmeal> page = setmealDao.findPage(queryString);
        // 组织响应数据
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        //先查询redis
        String setmeals = jedisPool.getResource().get("setmeals");

        if (setmeals == null || "".equals(setmeals)) {//缓存未命中
            List<Setmeal> setmealList = setmealDao.findAll();
            //转换json格式:字符串类型
            String jsonString = JSON.toJSONString(setmealList);
            //查询结果放进jedis缓存区
            jedisPool.getResource().set("setmeals", jsonString);
            return setmealList;
        }

        //缓存命中
        //json格式转list对象,对象要实现序列化
        List<Setmeal> setmealList = JSON.parseArray(setmeals, Setmeal.class);

        return setmealList;
    }


    // 使用<resultMap>和<collectioin>
//    @Override
//    public Setmeal findById(Integer id) {
//        Setmeal setmeal = setmealDao.findById(id);
//        return setmeal;
//    }

    // 不使用<resultMap>和<collectioin>，使用业务代码
    @Autowired
    CheckGroupDao checkGroupDao;

    @Autowired
    CheckItemDao checkItemDao;

    @Override
    public Setmeal findById(Integer id) {
        //从缓存中查找全部的套餐
        String setmealStr = jedisPool.getResource().get(id + "");

        if (setmealStr == null || "".equals(setmealStr)) {//缓存未命中
            //查找数据库
            Setmeal setmeal = setmealDao.findById(id);
            // 业务代码完成封装
            List<CheckGroup> checkgroups = checkGroupDao.findCheckGroupListBySetmealId(id);
            if (checkgroups != null && checkgroups.size() > 0) {
                for (CheckGroup checkgroup : checkgroups) {
                    List<CheckItem> checkitems = checkItemDao.findCheckItemListByCheckGroupId(checkgroup.getId());
                    checkgroup.setCheckItems(checkitems);
                }
            }
            setmeal.setCheckGroups(checkgroups);
            String jsonString = JSON.toJSONString(setmeal);
            //缓存到redis,根据id区分
            jedisPool.getResource().set(id + "", jsonString);

            return setmeal;
        }

        Setmeal setmeal = JSON.parseObject(setmealStr, Setmeal.class);
        return setmeal;
    }

    @Override
    public Setmeal findSetmealById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map> findSetmealOrderCount() {
        return setmealDao.findSetmealOrderCount();
    }


    @Override
    public List<Integer> findCheckgroupIds(Integer id) {
        return setmealDao.findCheckgroupIds(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.依据套餐id先删除关联中间表信息
        List<Integer> checkgroupIdsOld = setmealDao.findCheckgroupIds(setmeal.getId());
        if (checkgroupIdsOld != null && checkgroupIdsOld.size()>0) {
            setmealDao.deleteSetmealAndCheckGroupById(setmeal.getId());
        }
        //2.先查询出原数据库中img信息,删除redis中同时需同步redis信息
        Setmeal setmealOld = setmealDao.findById(setmeal.getId());
        if (setmealOld.getImg() != null) {
            this.deletePicFromRedis(setmealOld.getImg());
        }
        this.savePic2Redis(setmeal.getImg());
        //3.同步新增关联中间表
        if (checkgroupIds != null && checkgroupIds.length>0) {
            this.setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //4.最后编辑套餐
        setmealDao.edit(setmeal);
        //编辑后需清空移动端套餐缓存信息
        jedisPool.getResource().del("setmeals");
    }

    @Override
    public void deleteBySetmealId(Integer id) {
        //1.先确认关联中间表是否存在数据
        List<Integer> checkgroupIds = setmealDao.findCheckgroupIds(id);
        if (checkgroupIds != null) {
            throw  new RuntimeException("当前套餐与检查组关联,不能删除");
            //2.先删除中间表对应套餐id信息
//            setmealDao.deleteSetmealAndCheckGroupById(id);
        }
        //3.依据id获取到套餐对应信息,删除redis
        Setmeal setmeal = setmealDao.findById(id);
        if (setmeal.getImg() != null) {
            this.deletePicFromRedis(setmeal.getImg());
        }
        //4.删除套餐表对应的数据
        setmealDao.deleteSetmealById(id);
        //编辑后需清空移动端套餐缓存信息
        jedisPool.getResource().del("setmeals");
    }

    private void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkGroupIds) {
        for (Integer checkGroupId : checkGroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmealId",setmealId);
            map.put("checkGroupId",checkGroupId);
            setmealDao.addSetmealAndCheckGroup(map);
        }
    }

    private void savePic2Redis(String img) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
    }

    //从redis中删除img
    private void deletePicFromRedis(String img) {
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
    }
}
